package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.constant.insure.InsureConstant;
import com.itheima.sfbx.framework.commons.dto.basic.TreeItemVO;
import com.itheima.sfbx.framework.commons.dto.basic.TreeVO;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.NoProcessing;
import com.itheima.sfbx.insurance.dto.CategoryCoefficentVO;
import com.itheima.sfbx.insurance.dto.CategoryConditionVO;
import com.itheima.sfbx.insurance.dto.CategorySafeguardVO;
import com.itheima.sfbx.insurance.dto.CategoryVO;
import com.itheima.sfbx.insurance.mapper.CategoryMapper;
import com.itheima.sfbx.insurance.pojo.Category;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description：保险分类服务实现类
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    ICategoryConditionService categoryConditionService;

    @Autowired
    ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    ICategorySafeguardService categorySafeguardService;


    @Override
    public Page<CategoryVO> findPage(CategoryVO categoryVO, int pageNum, int pageSize) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public CategoryVO save(CategoryVO categoryVO) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public Boolean update(CategoryVO categoryVO) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //TODO
        return null;
    }

    @Override
    public List<CategoryVO> findList(CategoryVO query) {
        //构建查询条件，和page分页一样，可以整合
        List<Category> categorys = lambdaQuery().like(StrUtil.isNotBlank(query.getCategoryName()), Category::getCategoryName, query.getCategoryName())
                .eq(StrUtil.isNotBlank(query.getCategoryNo()), Category::getCategoryNo, query.getCategoryNo())
                .eq(StrUtil.isNotBlank(query.getCheckRule()), Category::getCheckRule, query.getCheckRule())
                .eq(StrUtil.isNotBlank(query.getDataState()), Category::getDataState, query.getDataState())
                .eq(StrUtil.isNotBlank(query.getParentCategoryNo()), Category::getParentCategoryNo, query.getParentCategoryNo()).list();
        List<Category> categorysHandler = Lists.newArrayList();
        //显示指定节点层
        if (!EmptyUtil.isNullOrEmpty(query.getNodeFloors())){
            categorys.forEach(n->{
                //NoProcessing就是根据No判断层级的一个工具类
                if (query.getNodeFloors().contains((long) (NoProcessing.processString(n.getCategoryNo()).length() / 3 - 1))){
                    categorysHandler.add(n);
                }
            });
        }else {
            categorysHandler.addAll(categorys);
        }
        //执行列表查询
        List<CategoryVO> categoryVOs = BeanConv.toBeanList(categorysHandler,CategoryVO.class);
        if (!EmptyUtil.isNullOrEmpty(categoryVOs)){
            Set<String> categoryNoSet = categoryVOs.stream().map(CategoryVO::getCategoryNo).collect(Collectors.toSet());
            //查询分类筛选项
            List<CategoryConditionVO> categoryConditionVOs = categoryConditionService.findListInCategoryNo(categoryNoSet);
            //查询分类保障项
            List<CategorySafeguardVO> categorySafeguardVOs = categorySafeguardService.findListInCategoryNo(categoryNoSet);
            //查询分类系数项
            List<CategoryCoefficentVO> categoryCoefficentVOs = categoryCoefficentService.findListInCategoryNo(categoryNoSet);
            //组合表单，双重for，也可以参考转Map的方式，自己选择，这里只是提供思路
            categoryVOs.forEach(n->{
                n.setCategoryConditionVOs(categoryConditionVOs.stream()
                        .filter(y->n.getCategoryNo().equals(y.getCategoryNo()))
                        .collect(Collectors.toList()));
                n.setCategoryCoefficentVOs(categoryCoefficentVOs.stream()
                        .filter(y->n.getCategoryNo().equals(y.getCategoryNo()))
                        .collect(Collectors.toList()));
                n.setCategorySafeguardVOs(categorySafeguardVOs.stream()
                        .filter(y->n.getCategoryNo().equals(y.getCategoryNo()))
                        .collect(Collectors.toList()));
            });
        }
        return categoryVOs;
    }



    @Override
    public TreeVO categoryTreeVO(String parentCategoryNo, String categoryType,String[] checkedCategoryNos) {
        //1.确定根节点
        parentCategoryNo = parentCategoryNo == null ? SuperConstant.ROOT_PARENT_ID : parentCategoryNo;
        //2.根据父节点查询所有子节点（包括自己）
        String head = NoProcessing.processString(parentCategoryNo);
        List<Category> categoryList = lambdaQuery().likeRight(Category::getCategoryNo, head)
                .eq(Category::getDataState, SuperConstant.DATA_STATE_0)
                .eq(StrUtil.isNotBlank(categoryType), Category::getCategoryType, categoryType)
                .list();
        if (CollUtil.isEmpty(categoryList)) {
            return new TreeVO();
        }
        //3.将categoryList转为List<TreeItemVO>
        List<TreeItemVO> treeItemVOList = categoryList.stream().map(x -> TreeItemVO.builder().id(x.getCategoryNo())
                .parentId(x.getParentCategoryNo())
                .label(x.getCategoryName())
                .build()).collect(Collectors.toList());
        //3.1将treeItemVOList转为map，key为父编号，value为子对象集合
        Map<String, List<TreeItemVO>> parentMap = treeItemVOList.stream().collect(Collectors.groupingBy(TreeItemVO::getParentId));
        //3.2遍历treeItemVOList绑定每个节点的关系
        for (TreeItemVO treeItemVO : treeItemVOList) {
            List<TreeItemVO> treeItemVOS = parentMap.get(treeItemVO.getId());
            treeItemVO.setChildren(treeItemVOS);
        }
        //3.3将根节点绑定上
        TreeVO treeVO = new TreeVO();
        treeVO.setItems(parentMap.get(parentCategoryNo));
        return treeVO;
    }

    @Override
    public String createCategoryNo(String parentCategoryNo) {
        CategoryVO categoryVO = CategoryVO.builder()
            .parentCategoryNo(parentCategoryNo)
            .build();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getParentCategoryNo,parentCategoryNo);
        List<Category> categoryList = list(queryWrapper);
        //无下属节点则创建下属节点
        if (EmptyUtil.isNullOrEmpty(categoryList)){
            return NoProcessing.createNo(parentCategoryNo,false);
        //有下属节点则累加下属节点
        }else {
            Long categoryNo = categoryList.stream()
                .map(category -> { return Long.valueOf(category.getCategoryNo());})
                .max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(categoryNo),true);
        }
    }

    /**
     * 人种榜险种榜分类
      * @param type
     */
    @Override
    public List<CategoryVO> categoryCheckRule(String type) {
        //判断是否是险种榜
        if(InsureConstant.checkIsInsureType(type)){
            List<CategoryVO> res = new ArrayList<>();
            //获取所有的险种榜
            List<String> allCheckRule = InsureConstant.getAllCheckRule();
            allCheckRule.forEach(e->{
                CategoryVO categoryVO = CategoryVO.builder().categoryNo(e).categoryName(InsureConstant.getRuleNameById(e)).build();
                res.add(categoryVO);
            });
            return res;
        }else{
            //说明是人种榜
            List<String> categoryNames = Arrays.asList("成年人", "少儿", "老人");
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Category::getCategoryName,categoryNames);
            queryWrapper.eq(Category::getDataState,SuperConstant.DATA_STATE_0);
            List<CategoryVO> res = BeanConv.toBeanList(list(queryWrapper), CategoryVO.class);
            return res;
        }
    }
}
